package com.such.kit.el;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Map;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import com.such.kit.Callable;
import com.such.kit.cache.CacheCommons;
import com.such.kit.el.support.ExpressionEngine;

/**
 * @author SUCH
 * <pre>
 * 基于 Mvel 的表达式引擎实现
 * </pre>
 */
public class MvelExpressionEngine implements ExpressionEngine {

	private static ParserContext context = new ParserContext();
	private static String expressionCache = CacheCommons.buildCacheName(MvelExpressionEngine.class);

	@Override
	public <Return, Input> Return execute(final String expression, Map<String, Input> inputs) throws Exception {
		Serializable compiled = CacheCommons.get(expressionCache, expression, new Callable<String, Serializable>() {
			@Override
			public Serializable call(String param) throws Exception {
				return MVEL.compileExpression(expression, context);
			}
		});
		return (Return) MVEL.executeExpression(compiled, inputs);
	}

	@Override
	public void register(Object... args) {
		String name = (String) args[0];
		Method method = (Method) args[1];
		context.addImport(name, method);
	}

}
